package com.epam.task.web.service.command;

import com.epam.task.web.entity.User;
import com.epam.task.web.service.AbstractAction;
import com.epam.task.web.util.Encryption;
import com.epam.task.web.util.logging.LoggerUtil;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Login extends AbstractAction {

    LoggerUtil logger = new LoggerUtil(Logger.getLogger(Login.class.getClass()));

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) {
        Encryption encryption = new Encryption();
        String username = request.getParameter("username");
        String password = encryption.getHashCode(request.getParameter("password"));
        ResultSet resultSet = find("oc_user", "username", "password", username, password);
        User user;

        if (resultSet != null) {
            try {
                if (resultSet.first()) {
                    long id = (long) resultSet.getObject("user_id");
                    user = createUserById(id);

                    request.getSession().setAttribute("oc_user", user);
                    switch ((int) resultSet.getObject("user_group_id")) {
                        case User.MANAGER:
                            return "/managerPage.jsp";
                        case User.CUSTOMER:
                            return "/customerPage.jsp";
                        default:
                            request.getSession().setAttribute("errorMessage", "Invalid field 'Group'");
                            return "/error.jsp";
                    }
                }
            } catch (SQLException exception) {
                logger.getExceptionTextFileLogger().error(exception);
            }
        } else {
            request.getSession().setAttribute("errorMessage", "Invalid username/password.");
            return "/error.jsp";
        }

        request.getSession().setAttribute("errorMessage", "Data base error.");
        return "/error.jsp";
    }

}
